package com.lean.android.ad.utils

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow

object NetworkUtils : ConnectivityManager.NetworkCallback() {

    private val _networkStateFlow = MutableStateFlow(false)

    val networkStateFlow = _networkStateFlow.asStateFlow()

    fun init(context: Context) {
        val networkManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkRequest = NetworkRequest.Builder()
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .build()
        networkManager.registerNetworkCallback(networkRequest, this)
    }

    fun isNetworkConnected() = _networkStateFlow.value

    override fun onAvailable(network: Network) {
        _networkStateFlow.value = true
        AdLog.d(AdLog.AdHttpTag, "network onAvailable")
    }

    override fun onLost(network: Network) {
        _networkStateFlow.value = false
        AdLog.d(AdLog.AdHttpTag, "network onLost")
    }
}